/**
 * \class CBroadcast
 * \brief This is a file transfer class in a broadcast way.
 * \version 0.3.2
 *
 * \author Woo-Hyun Kim (woorung@nhncorp.com, woorung@gmail.com)
 * \author http://blog.naver.com/wisereign .
 *
 * \date 2008/6/18
 */
#include "CBroadcast.h"
//-----------------------------------------------------------------
/**
  @brief CBroadcast constructor
  @return n/a
 */
//-----------------------------------------------------------------
CBroadcast::CBroadcast(char *host, int port) 
{
	this->host = host;
	this->port = port;
}
//-----------------------------------------------------------------
/**
  @brief CBroadcast destructor
  @return n/a
 */
//-----------------------------------------------------------------
CBroadcast::~CBroadcast() 
{
}
//-----------------------------------------------------------------
/**
  @brief file will be broadcasted to all of the node
  @return success(>0) or failure(<1)
 */
//-----------------------------------------------------------------
int CBroadcast::broadcast(char *file) 
{
	return broadcast(file, NULL);
}
//-----------------------------------------------------------------
/**
  @brief file will be broadcasted to all of the node
  @return success(>0) or failure(<1)
 */
//-----------------------------------------------------------------
int CBroadcast::broadcast(char *file, char *repository_path) 
{
	vector<CServiceInfo> all;
	
	CNary nary((char *)host.c_str(), port);
	nary.configure(CUBE_SERVICE_TASK);
	all = nary.lookup(all);

#ifdef DEBUG
	cout << "###########################################################" << endl;
	for(int i=0;i<all.size();i++) cout << all[i].getIP() << ":" << all[i].getPort() << endl;
	cout << "###########################################################" << endl;
	cout << endl;
#endif

	int success = 0;

	// transfer file to only a machine
	string pre_ip = "";
	string cur_ip = "";
	for(int i=0;i<all.size();i++) {
		cur_ip = all[i].getIP();

		if(pre_ip!=cur_ip) {
			CFileProxy file_proxy(all[i].getIP(), all[i].getPort());

			if(repository_path!=NULL) file_proxy.repository(repository_path);

			int status = file_proxy.put(file);
			if(status<1) {
				cerr << "cannot broadcast " << file << " to " << all[i].getIP() << ":" << all[i].getPort() << endl;

				exit(success);
			}
		}

		pre_ip = cur_ip;

		success++;
	}

	return success;
}
//-----------------------------------------------------------------
